<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'pkg:basPkgM:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #basPkgCList>
        <BasicTable
          @register="registerBasPkgCTable"
          @row-click="handleBasPkgCRowClick"
        />
        <a-button class="mt-2" @click="handleBasPkgCAdd" v-auth="'pkg:basPkgM:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsPkgBasPkgMForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasPkgM, basPkgMSave, basPkgMForm } from '/@/api/pkg/basPkgM';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('pkg.basPkgM');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<BasPkgM>({} as BasPkgM);
  
  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增包装信息') : t('编辑包装信息'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('产品代号'),
      field: 'ccode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('包装名称'),
      field: 'cname',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('存货编码'),
      field: 'invCode',
      component: 'Input',
      // componentProps: {
      //   maxlength: 100,
      //   selectType: 'basInvSelect',
      // },
      required: true,
      // 有值时，禁用
      dynamicDisabled: (values: any) => {
        return !!values.model.invCode;
      },
      // dynamicDisabled: true,
    },
    {
      label: t('容量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('条码类型'),
      field: 'barType',
      component: 'Select',
      componentProps: {
        dictType: 'btdm_bar_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('是否需要绑定'),
      field: 'bbind',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('是否验真'),
      field: 'blink',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('打印张数上浮比例'),
      field: 'floatRatio',
      component: 'Input',
      componentProps: {
        maxlength: 10,
      },
    },
    {
      label: t('导出类型'),
      field: 'exportType',
      component: 'Select',
      componentProps: {
        dictType: 'btdm_export_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('导出二维码尺寸'),
      field: 'barSize',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
    },
    {
      label: t('追溯地址'),
      field: 'fromUrl',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
    },
    {
      label: t('包装信息子表'),
      field: 'basPkgCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'basPkgCList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerBasPkgCTable, basPkgCTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleBasPkgCDelete.bind(this, record),
          },
          auth: 'pkg:basPkgM:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setBasPkgCTableData(_res: Recordable) {
    basPkgCTable.setColumns([
      // {
      //   title: t('存货编码'),
      //   dataIndex: 'invCode',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 100,
      //   },
      //   editRule: true,
      // },
      {
        title: t('容量'),
        dataIndex: 'iqty',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: true,
      },
      {
        title: t('条码类型'),
        dataIndex: 'barType',
        width: 130,
        align: 'center',
        dictType: 'btdm_bar_type',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'btdm_bar_type',
          allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('是否需要绑定'),
        dataIndex: 'bbind',
        width: 130,
        align: 'center',
        dictType: 'sys_yes_no',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_yes_no',
          allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('是否验真'),
        dataIndex: 'blink',
        width: 130,
        align: 'center',
        dictType: 'sys_yes_no',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_yes_no',
          allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('打印张数上浮比例'),
        dataIndex: 'floatRatio',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 10,
        },
        editRule: false,
      },
      {
        title: t('导出类型'),
        dataIndex: 'exportType',
        width: 130,
        align: 'center',
        dictType: 'btdm_export_type',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'btdm_export_type',
          allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('导出二维码尺寸'),
        dataIndex: 'barSize',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: false,
      },
      {
        title: t('追溯地址'),
        dataIndex: 'fromUrl',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },
      {
        title: t('层级'),
        dataIndex: 'level',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: true,
      },
    ]);
    basPkgCTable.setTableData(record.value.basPkgCList || []);
  }

  function handleBasPkgCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleBasPkgCAdd() {
    basPkgCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleBasPkgCDelete(record: Recordable) {
    basPkgCTable.deleteTableDataRecord(record);
  }

  async function getBasPkgCList() {
    let basPkgCListValid = true;
    let basPkgCList: Recordable[] = [];
    for (const record of basPkgCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        basPkgCListValid = false;
      }
      basPkgCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of basPkgCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      basPkgCList.push({
        ...record,
        status: '1',
      });
    }
    if (!basPkgCListValid) {
      throw { errorFields: [{ name: ['basPkgCList'] }] };
    }
    return basPkgCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    // console.log('data', data);
    // data = {
    //   ...data.record,
    //   ...data.isNewRecord,
    // };
    // console.log('data', data);
    const res = await basPkgMForm(data);
    record.value = (res.basPkgM || {}) as BasPkgM;
    record.value.__t = new Date().getTime();
    // record.value.invCode = data.cinvcode;
    // if (data.isNewRecord) {
    //   record.value.isNewRecord = true;
    // }
    if (data.record) {
      record.value.invCode = data.record.cinvcode;
      record.value.isNewRecord = true;
    }
    setFieldsValue(record.value);
    setBasPkgCTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        ccode: record.value.ccode,
      };
      data.basPkgCList = await getBasPkgCList();
      // console.log('submit', params, data, record);
      const res = await basPkgMSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
